package view.controller;


import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import lombok.SneakyThrows;
import utils.Connect;
import utils.Group;
import utils.User;
import utils.MessageBubble;
import view.AddNewFriend;
import view.CreateGroup;
import view.MainWindow;
import view.NewFriend;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author
 */
public class MainWindowController implements Initializable {

    @FXML
    public CheckBox checkBox1;
    @FXML
    public CheckBox checkBox2;
    @FXML
    private ListView<Object> groupChatListView;
    @FXML
    private ListView<Object> groupMessageListView;
    @FXML
    private TextArea groupTestArea;
    @FXML
    private Button groupSendButton;
    @FXML
    public  Label groupName;


    @FXML
    private ListView<Object> friendListView;
    @FXML
    private ListView<Object> friendChatListView;
    @FXML
    private ListView<Object> friendMessageListView;


    @FXML
    private TextField url;
    @FXML
    private ImageView imageView;
    @FXML
    private Button loadImage;
    @FXML
    private Button setHead;

    @FXML
    private Tab headTab;

    @FXML
    private Button sendButton;
    @FXML
    private Label gender;
    @FXML
    private Label diqu;
    @FXML
    private Label gender1;
    @FXML
    private Label beizhu1;

    @FXML
    private ImageView headphoto;

    @FXML
    private Label account1;

    @FXML
    private Label beizhu;

    @FXML
    private Label diqu1;

    @FXML
    private Label account;

    @FXML
    private Label userName1;

    @FXML
    private Label friendName;
    @FXML
    private TabPane tabPane;


    @FXML
    private Tab tab3;

    @FXML
    private Tab tab1;

    @FXML
    private Tab tab2;

    @FXML
    private TextArea testArea;

    public static ObservableList<Object> friendList1;
    public static ObservableList<Object> chatList1;
    public static ObservableList<Object> groupList1;

    public static List<User> friends;
    public static User chooseUser;
    public static ObservableList<Object> chooseFriendMessagePage;
    public static ArrayList<ObservableList<Object>> friendMessagePageList = new ArrayList<>();

    public static List<Group> groups;
    public static Group chooseGroup;
    public static ObservableList<Object> chooseGroupMessagePage;
    public static ArrayList<ObservableList<Object>> groupMessagePageList = new ArrayList<>();


    @SneakyThrows
    @Override
    public void initialize(URL location, ResourceBundle resources) {

        MainWindow.getMainWindow().setFriendListView(friendListView);
        MainWindow.getMainWindow().setGroupName(groupName);
        MainWindow.getMainWindow().setFriendName(friendName);
        MainWindow.getMainWindow().setHeadTab(this.headTab);

        tabPane.setTabMaxHeight(200);
        tabPane.setTabMaxWidth(200);
        tabPane.getSelectionModel().select(tab1);
        ImageView iv = new ImageView("file:photo/" + MainWindow.getMainWindow().getUser().getAccount() + ".png");
        iv.setFitHeight(50);
        iv.setFitWidth(50);
        headTab.setGraphic(iv);
        headTab.setStyle("-fx-background-color: rgb(51,51,51)");
        headTab.setText("  ");
        setTabImage(tab1,"image/mainWindow/vx.png");
        setTabImage(tab2,"image/mainWindow/friend.png");
        setTabImage(tab3,"image/mainWindow/group.png");

        int y=265,x=55;
        tabPane.setOnMouseMoved(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if (event.getSceneY() <= y && event.getSceneX() <= x) {
                    tabPane.setCursor(Cursor.HAND);
                } else {
                    tabPane.setCursor(Cursor.DEFAULT);
                }
            }
        });
        friendListView.setItems(friendList1);
        friendChatListView.setItems(chatList1);
        groupChatListView.setItems(groupList1);
        friendListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            int num = friendListView.getSelectionModel().getSelectedIndex();//获取点击的序号
            User user;
            int bound=4;
            int addNewFriend=1;
            int newFriend=2;
            int createGroup=3;
            if (num < bound) {
                user = MainWindow.getMainWindow().getUser();
            } else {
                user = friends.get(num - 4);
            }
            if (num == addNewFriend) {
                new AddNewFriend();
            }else if (num == newFriend) {
                new NewFriend();
                try {
                    NewFriend.getNewFriend().fun();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else if(num==createGroup){
                new CreateGroup();
            }
            userName1.setText(user.getName());//用户名
            account1.setText(user.getAccount());//账号
            diqu1.setText(user.getAddress());//地址
            gender1.setText(user.getSex());//性别
            beizhu1.setText("无");//备注
            Image p = new Image(String.format("file:photo/%s.png", user.getAccount()));
            headphoto.setImage(p);//头像
        });
        //点击加载消息
        friendChatListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            int num = friendChatListView.getSelectionModel().getSelectedIndex();//获取点击的序号
            chooseUser = friends.get(num);//获取该消息信息
            chooseFriendMessagePage = friendMessagePageList.get(num);
            friendMessageListView.setItems(chooseFriendMessagePage);
            friendMessageListView.scrollTo(chooseFriendMessagePage.size() - 1);
            friendName.setText(chooseUser.getName());
        });
        //点击加载群
        groupChatListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            int num = groupChatListView.getSelectionModel().getSelectedIndex();
            try {
                chooseGroup = groups.get(num);
                chooseGroupMessagePage = groupMessagePageList.get(num);
            }catch (Exception e){

            }
            groupMessageListView.setItems(chooseGroupMessagePage);
            groupMessageListView.scrollTo(chooseGroupMessagePage.size() - 1);
            groupName.setText(chooseGroup.getGroupName());
        });

    }

    public void setTabImage(Tab tab,String url){

        ImageView iv=new ImageView(url);
        iv.setFitHeight(35);
        iv.setFitWidth(35);
        tab.setGraphic(iv);
        tab.setText(" ");

    }

    public void sendMessageToFriend(MouseEvent event) {
        int num = friends.indexOf(chooseUser);
        friendMessageListView.setItems(chooseFriendMessagePage);
        String message = testArea.getText();
        testArea.clear();
        if(checkBox1.isSelected()) {
            message=message.substring(0,message.length()-1);
        }
        chooseFriendMessagePage.add(new MessageBubble().setTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        chooseFriendMessagePage.add(new MessageBubble().setOnRight(message, MainWindow.getMainWindow().getUser().getAccount()));
        if (num > 0) {
            friendList1.add(4,MainWindowController.friendList1.remove(num+4));
            chatList1.add(0, chatList1.remove(num));
            friends.add(0, friends.remove(num));
            friendMessagePageList.add(0, friendMessagePageList.remove(num));
        }
        friendChatListView.getSelectionModel().selectFirst();
        chooseFriendMessagePage = friendMessagePageList.get(0);
        friendMessageListView.scrollTo(chooseFriendMessagePage.size() - 1);
        Connect connect = Connect.getConnect();
        try {
            connect.sendMessageToFriend(MainWindow.getMainWindow().getUser(), chooseUser, message);
            System.out.println("发送消息完成");
        } catch (IOException e) {
            System.out.println("发送消息失败");
        }
    }

    public void sendMessageToGroup(MouseEvent event) {
        int num = groups.indexOf(chooseGroup);
        groupMessageListView.setItems(chooseGroupMessagePage);
        String message = groupTestArea.getText();
        groupTestArea.clear();
        if(checkBox2.isSelected()) {
            message=message.substring(0,message.length()-1);
        }
        chooseGroupMessagePage.add(new MessageBubble().setTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        chooseGroupMessagePage.add(new MessageBubble().setOnRight(message, MainWindow.getMainWindow().getUser().getAccount()));
        if (num > 0) {
            groupList1.add(0, groupList1.remove(num));
            groups.add(0, groups.remove(num));
            groupMessagePageList.add(0, groupMessagePageList.remove(num));
        }
        groupChatListView.getSelectionModel().selectFirst();
        chooseGroupMessagePage = groupMessagePageList.get(0);
        groupMessageListView.scrollTo(chooseGroupMessagePage.size() - 1);
        Connect connect = Connect.getConnect();
        try {
            connect.sendMessageToGroup(MainWindow.getMainWindow().getUser(), chooseGroup, message);
            System.out.println("发送消息完成");
        } catch (IOException e) {
            System.out.println("发送消息失败");
        }
    }


    @FXML
    private void getImage(MouseEvent event) {
        if (url.getText() != null) {
            Image image = new Image(url.getText());
            imageView.setImage(image);
        }
    }

    public void loadImage(DragEvent dragEvent) {
        Dragboard dragboard = dragEvent.getDragboard();
        if (dragboard.hasFiles()) {
            String path = dragboard.getFiles().get(0).getAbsolutePath();
            path = "file:" + path;
            url.setText(path);
            this.getImage(null);
        }
    }

    public void setMouse(DragEvent dragEvent) {
        dragEvent.acceptTransferModes(TransferMode.ANY);
    }

    @FXML
    public void testAreaKeyPressed(KeyEvent keyEvent) {
        if (checkBox1.isSelected() && keyEvent.getCode() == KeyCode.ENTER) {
            this.sendMessageToFriend(null);
        }
    }
    @FXML
    public void groupTestAreaKeyPressed(KeyEvent keyEvent) {
        if (checkBox2.isSelected() && keyEvent.getCode() == KeyCode.ENTER) {
            this.sendMessageToGroup(null);
        }
    }
}